<template>
  <el-dialog
    v-model="showDialog"
    :title="title"
    :append-to-body="true"
    :width="width"
    @closed="closeDialog"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <super-form
      :formAndTable="false"
      ref="materialDialogRef"
      v-bind="formOption"
      :modelValue="formData"
      :rules="formRules"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog()"> 取 消 </el-button>
        <el-button type="primary" :loading="loading" @click.stop="handleSubmit" @keyup.enter="keyDown">
          确 定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, useTemplateRef } from "vue";
import SuperForm from "@/components/SuperForm/index.vue";
import { FormOption } from "@/components/SuperForm/formType";
import { type FormRules } from "element-plus";
import { FormMaterial } from "./formConfig";
import { addMaterial, updateMaterial } from "@/api/materialFile";
interface Props {
  width?: number; // 宽度
  title?: string; // 标题
  type: string; // add | edit
}
const { width = 800, title, type } = defineProps<Props>();

const emits = defineEmits<{
  handleSubmit: [_row: any];
  handleClose: any;
}>();
// 弹窗
const showDialog = ref<boolean>(false);
const loading = ref<boolean>(false);
// 表单ref实例
const materialDialogRef = useTemplateRef<any>("materialDialogRef");
// 表单
const formData = ref<any>({});
const formOption = ref<FormOption>({formItems: []});
const formRules = ref<FormRules>({});
// 打开
const openDialog = (data: any = {}): void => {
  const formMaterial = new FormMaterial();
  formMaterial.getFormOption().finally(() => {
    formRules.value = formMaterial.formRules;
    formOption.value = formMaterial.formOption;
    Object.assign(formData.value, formMaterial.formData, { ...data });
    showDialog.value = true;
    loading.value = false;
  });
  nextTick(() => {
    window.addEventListener("keydown", keyDown);
  });
};
// 关闭
const closeDialog = (bool: boolean = false): void => {
  materialDialogRef.value?.ruleFormRef?.resetFields();
  showDialog.value = false;
  loading.value = false;
  formData.value = {};
  emits("handleClose", bool);
  window.removeEventListener("keydown", keyDown, false);
};
// 表单提交
const handleSubmit = (): void => {
  materialDialogRef.value.ruleFormRef.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const params = {
        name: formData.value.name,
        materialUnitId: formData.value.materialUnitId,
        materialTypeId: formData.value.materialTypeId,
        materialId: formData.value?.id || undefined,
        code: formData.value.code,
      };
      const fnMaterial = type === "edit" ? updateMaterial : addMaterial;
      fnMaterial(params)
        .then((res: any) => {
          if (res) {
            ElMessage.success(`${type === "edit" ? "编辑成功" : "新增成功"}`);
            closeDialog(true);
          }
        })
        .catch(() => {
          loading.value = false;
        });
    } else {
      loading.value = false;
    }
  });
};
// 键盘事件
const keyDown = (e: any) => {
  if (e.keyCode === 13) {
    handleSubmit();
  }
};

defineExpose({
  closeDialog,
  openDialog,
});
</script>
